package hk.linkcredit.awardservice.rocketmq.transaction;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import hk.linkcredit.awardservice.common.constant.Status;
import hk.linkcredit.awardservice.common.exception.BizException;
import hk.linkcredit.common.rocketmq.listener.ITransactionHandler;
import hk.linkcredit.awardservice.award.domain.entity.AwardRecord;
import hk.linkcredit.awardservice.award.domain.vo.SmsSendData;
import hk.linkcredit.awardservice.award.service.IAwardRecordService;
import hk.linkcredit.awardservice.award.service.impl.AwardSmsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.RoundingMode;
import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class AwardActivityTransactionHandler implements ITransactionHandler<List<AwardRecord>> {

    IAwardRecordService awardRecordService;

    AwardSmsService awardSmsService;

    public static final String SMS_ACTIVITY_AWARD = "main_bns_ntce";


    @Override
    public void processTransaction(List<AwardRecord> recordList, String msgId) {
        boolean saveBatch = awardRecordService.saveBatch(recordList);
        if (!saveBatch) throw new BizException(Status.DB_OPERATION_FAILED);
        this.sendSms(recordList);
        //处理事务
        log.info("插入数据库成功，推送奖励分润消息");
    }

    @Override
    public boolean checkTransaction(String bizId, String msgId) {
        //查询事务是否处理成功
        long bizCount = awardRecordService.count(new QueryWrapper<AwardRecord>().eq("serial_no", bizId));
        log.info("本地事务提交{}", bizCount > 0 ? "成功" : "失败");
        return bizCount > 0;
    }

    public void sendSms(List<AwardRecord> recordList) {
        recordList.forEach(e -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("lastName", e.getLastName());
            jsonObject.put("commission", e.getAwardAmount().setScale(2, RoundingMode.HALF_DOWN));
            SmsSendData smsData = SmsSendData.builder().noticeType("notice")
                    .smsType(SMS_ACTIVITY_AWARD)
                    .phoneNumber(e.getRegisterPhone()).countryCode("+234")
                    .smsParam(jsonObject).build();
            awardSmsService.asyncSend(smsData);
        });
    }


}
